package com.lq.filter;

import javax.servlet.*;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@javax.servlet.annotation.WebFilter("/*")
public class WebFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = uri.substring(contextPath.length());

        // 白名单列表，需要对注册，登陆页面放行，需要对登陆和注册serlvet请求放行，同时也需要对异步请求放行
        List<String> whiteList = Arrays.asList(
                "/login.jsp",
                "/register.jsp",
                "/user/checkUserName",
                "/user/getProfile",
                "/user/verification",
                "/user/login",
                "/user/register"
        );

        // 白名单放行
        if (whiteList.contains(path)) {
            chain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession(false);
            //这里一定注意，因为在登陆的时候，服务器是给用户分配了sessioin的，并且将验证码内容放在了session当中，但是此时session中并没有user对象
            //一旦登陆成功之后，就会把new对应的user对象并放在了session中，这里如果session不为空，且还有user对象则就为登陆状态就放行
            if (session != null && session.getAttribute("user") != null) {
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(contextPath + "/login.jsp");
            }
        }
    }
}


